
package com.ezops.poc.util;

import java.io.File;

import javax.annotation.PostConstruct;

import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.DecisionTableConfiguration;
import org.drools.builder.DecisionTableInputType;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderError;
import org.drools.builder.KnowledgeBuilderErrors;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.io.ResourceFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class RulesLoader {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(RulesLoader.class);
	public static KnowledgeBase ezopsRuleBase;

	public final static String RULEFILEDIR = System.getProperty("user.home")
			+ File.separator + "EZOPS";

	public final static String EZOPS_RULE_SET = RULEFILEDIR + File.separator
			+ File.separator + "ezopsRules.xls";

	@PostConstruct
	protected void init() {

		LOGGER.info("############ - Initializing - ############");

		KnowledgeBase kbase = knowledgeBuilder(EZOPS_RULE_SET);
		ezopsRuleBase = kbase;

		LOGGER.info("############ - Initialization completed - ############");
	}

	/**
	 * @param kbuilder1
	 * @param config1
	 * @return
	 * @throws IllegalArgumentException
	 */
	private KnowledgeBase knowledgeBuilder(String ruleSet)
			throws IllegalArgumentException {
		KnowledgeBuilder kbuilder = KnowledgeBuilderFactory
				.newKnowledgeBuilder();
		DecisionTableConfiguration config = KnowledgeBuilderFactory
				.newDecisionTableConfiguration();
		config.setInputType(DecisionTableInputType.XLS);
		kbuilder.add(ResourceFactory.newFileResource(ruleSet),
				ResourceType.DTABLE, config);
		KnowledgeBuilderErrors errors = kbuilder.getErrors();
		if (errors.size() > 0) {
			for (KnowledgeBuilderError error : errors) {
				LOGGER.error("" + error);
			}
			throw new IllegalArgumentException("Could not parse knowledge.");
		}

		KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
		kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
		return kbase;
	}

}
